<template>
  <div class="app-container">
    <div v-if="isSearchBtn" class="filter-container">
      <el-input v-model="listQuery.title" placeholder="关键词" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.is_hid" placeholder="状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
    </div>
    <div style="background: #FFFFFF;padding: 0.625rem;">
      <div style="margin-bottom: 0.625rem;">
        <el-button v-permission="'memberlabel@add'" class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
          新增
        </el-button>
        <el-button v-show="isShowBtn" v-permission="'memberlabel@el'" class="filter-item" type="danger" icon="el-icon-delete" @click="handleDeleteAll">
          批量删除
        </el-button>
        <el-button circle style="float: right;" icon="el-icon-search" @click="showBtn" />
        <el-button circle style="float: right;" icon="el-icon-refresh" @click="getList" />
      </div>
      <el-table
        v-loading="listLoading"
        :data="list"
        :header-cell-style="{background:'#eee',color:'#606266'}"
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
        @select-all="showDeleteBtn"
        @select="showDeleteSelectBtn"
      >
        <el-table-column
          align="center"
          type="selection"
        />
        <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标题" align="center">
          <template slot-scope="{row}">
            <span class="link-type" @click="handleUpdate(row)">{{ row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column label="排序" min-width="80px">
          <template slot-scope="{row}">
            <span>{{ row.sort }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" class-name="status-col">
          <template slot-scope="{row}">
            <el-switch
              :value="row.is_hid===0?'0':'1'"
              active-text="启用"
              inactive-text="禁用"
              active-value="0"
              inactive-value="1"
              @change="isShow(row.is_hid,row.id,row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template slot-scope="{row}">
            <span>{{ row.add_time }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="180" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button v-permission="'memberlabel@edit'" title="编辑" type="primary" icon="el-icon-edit" circle @click="handleUpdate(row)" />
            <el-button v-if="row.status!='deleted'" v-permission="'memberlabel@del'" title="删除" icon="el-icon-delete" circle type="danger" @click="handleDelete(row,$index)" />
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="listQuery.p" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="70px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="temp.title" maxlength="150" placeholder="请输入2-150字符的标题" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="temp.sort" :min="0" :max="1000" label="排序" />
        </el-form-item>
        <el-form-item label="状态" prop="is_hid">
          <el-select v-model="statusOptions[temp.is_hid]" class="filter-item" placeholder="请选择状态">
            <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-switch-button" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button icon="el-icon-s-promotion" type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList, disable, enable, create, update, del } from '@/api/label'
import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'

const calendarTypeOptions = [
  { key: '0', display_name: '正常' },
  { key: '1', display_name: '禁用' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'PagePermission',
  components: { Pagination },
  directives: { waves, permission },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        p: 1,
        limit: 10,
        title: undefined,
        is_hid: undefined,
        sort: '+id'
      },
      calendarTypeOptions,
      statusOptions: ['启用', '禁用'],
      temp: {
        id: undefined,
        title: '',
        sort: '',
        is_hid: '0'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        title: [{ required: true, message: '名称必填', trigger: 'change' }]
      },
      ids: [],
      isShowBtn: false,
      isSearchBtn: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    isShow(isShow, id, row) {
      const data = {}
      data.ids = id
      if (isShow === false) {
        disable(data).then(response => {
          row.is_hid = '1'
          this.$message({
            message: response.message,
            type: 'success'
          })
        })
      } else {
        enable(data).then(response => {
          row.is_hid = '0'
          this.$message({
            message: response.message,
            type: 'success'
          })
        })
      }
    },
    showBtn() {
      this.isSearchBtn = this.isSearchBtn === false
    },
    showDeleteBtn: function(selection) {
      this.ids = []
      Object.keys(selection).forEach((key) => {
        this.ids.push(selection[key].id)
      })
      this.isShowBtn = this.ids.length > 0
    },
    showDeleteSelectBtn: function(selection, row) {
      this.ids = []
      Object.keys(selection).forEach((key) => {
        this.ids.push(selection[key].id)
      })
      this.isShowBtn = this.ids.length > 0
    },
    handleDeleteAll() {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {}
        data.ids = this.ids
        this.listLoading = true
        del(data).then(response => {
          this.ids = []
          this.getList()
          this.isShowBtn = false
          this.listLoading = false
          this.$message({
            message: response.message,
            type: 'success'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleFilter() {
      this.listQuery.p = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetQuery() {
      this.listQuery = {
        p: 1,
        limit: 10,
        title: undefined,
        is_hid: undefined,
        sort: '+id'
      }
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        sort: 0,
        is_hid: '0'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          create(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          update(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const tempData = {}
        tempData.ids = row.id
        del(tempData).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

<style>
  .filter-item{
    margin-right: 0.3125rem;
  }
</style>
